import $ from "jquery";
import Vue from "vue";

import EnvConf from "@/config/envConf.js";
import EditorDefaultConf from "@/config/editorDefaultConfig.js";
import BaseUtil from "@/utils/baseUtil.js";

/* eslint-disable */
export default {

    data() {
        return {

            materialObj: {},

            searchType: "",

            dropObj: null,

            targetObj: null,

            slideObj: {},

            slideFlag: 0,

            paresModelObj: []
        }
    },

    async created() {

        const urlParams = BaseUtil.paresUrlSearchStr();
        const token = BaseUtil.getCookie("token");

        if (urlParams !== null && urlParams.hasOwnProperty("modelId") && token) {

            this.$root.$emit("fileParsing");

            const _this = this;
            const urlConfig = EnvConf[process.env.NODE_ENV];

            let url = "";
            const modelId = urlParams['modelId'];
            const modelState = urlParams['modelState'];
            const time = Date.now();

            url += `${urlConfig.baseUrl}:${urlConfig.port}${urlConfig.getModelFatDetail}?`;
            url += `modelId=${modelId}&_=${time}&token=${token}&visitStatus=${modelState}`;

            try {

                const modelInfo = await this.$http.query({url: url});

                if (modelInfo.success) {

                    if (modelInfo.result.modelDto && modelInfo.result.modelDto.modelUrl) {

                        const modelUrl = modelInfo.result.modelDto.modelUrl;
                        const fileType = BaseUtil.getFileType(modelUrl);

                        const resData = await this.$http.query({
                            url: modelUrl,
                            responseType: this.$http.responseType.arraybuffer
                        });

                        if (fileType.toLowerCase() === "halo") {

                            const zipFileLoaded = new JSZip(resData, { "uint8array": true });
                            const keys = Object.keys(zipFileLoaded.files);
                            const contents = zipFileLoaded.files[keys[0]].asText();
                            const metaObj = JSON.parse(contents);

                            await _this.createHaloScript(metaObj.cfg.version);

                            _this.initViewPort();

                            _this.initHaloProject();

                            const meta = Halo.ResourceManager.unzip(resData);

                            _this.handleModelFileData(meta, modelInfo.result.modelDto.fileName);

                        } else if (fileType.toLowerCase() === "fbx") {

                            const file = new Blob([resData], { type: "text/plain" });
                            file.name = modelInfo.result.modelDto.fileName;

                            if (!window.Halo) {

                                await _this.createHaloScript("new");

                                _this.initViewPort();

                                this.initHaloProject();
                            }

                            BaseUtil.parseFbx(file, (group) => {

                                _this.createSelectObjView(Editor.getDepsNObj(group), group);

                                $(".uploadFileView .uploadCenter>span").show().eq(1).find("span").text(file.name);

                                this.$root.$emit("haloLoaded");
                                this.$root.$emit("fileParsed", modelInfo.result.modelDto.fileName);
                            });


                        } else {
                            _this.$message.warning("当前编辑器只支持halo或fbx类型文件");
                            _this.$root.$emit("fileParsed", "");
                        }

                    } else {
                        this.$message.error("获取模型信息为空！");
                        _this.$root.$emit("fileParsed", "");
                    }

                } else {
                    this.$message.error("获取模型信息失败: " + modelInfo.errorMessage);
                    _this.$root.$emit("fileParsed", "");
                }

            } catch (e) {
                this.$message.error(e);
                _this.$root.$emit("fileParsed", "");
            }

        }
    },


    mounted() {

        if (!FileReader) {
            this.$message.error("当前浏览器不支持FileReader，请更新浏览器或使用最新版谷歌浏览器");
            return;
        }

        const _this = this;

        if (window.Halo) {
            _this.initViewPort();
        }

        $(() => {

            if (Vue.prototype.baseConfig) {
                _this.setViewPort();
            }

            _this.$root.$on("enterPick", _this.setMaterialMap);
        });
    },

    methods: {

        editedBtnClicked(e) {

            const typeList = ["translate", "rotate", "scale", "reset", "cancel"];

            let target = $(e.target);

            if (target[0].tagName.toUpperCase() !== 'BUTTON') {

                target = $(target).parent();

                target.addClass("buttonActive").siblings().removeClass("buttonActive");
            }

            const typeIndex = typeList[target.index()] ? typeList[target.index()] : "translate";

            if (target.index() < 3) this.changedObj(typeIndex);

            if (typeIndex === "cancel") this.onCancelClick();
            if (typeIndex === "reset") this.onResetClick();
        },

        onCancelClick () {
            if (this.$store.state.activeList.length > 0) {

                const info = this.$store.state.activeList[this.$store.state.activeList.length - 1];

                let value = {};

                let i = 0;
                for (i; i < info.paramList.length - 1; i++) {
                    value = value[info.paramList[i]] || info.target[info.paramList[i]] || 0;
                }

                value[info.paramList[info.paramList.length - 1]] = parseFloat(parseFloat(info.value).toFixed(2));

                this.$store.state.activeList.splice(this.$store.state.activeList.length - 1, 1);
            }
        },

        onResetClick () {

            if (Object.keys(this.$store.state.resetMap).length > 0) {

                const key = Object.keys(this.$store.state.resetMap)[0];
                const obj = this.$store.state.resetMap[key];

                switch (obj.type) {

                    case "Group": {
                        // Vue.prototype.baseConfig.model[obj.name] = this.$store.state.baseConfig.model[obj.name];
                        console.log(Vue.prototype.baseConfig.model[obj.name]);
                        console.log(obj);
                    }
                    break;

                }
            }
        },

        changedObj(type) {

            window.viewport.transmode(type);
        },

        createUploadFileEvent() {

            const _this = this;

            $("#fileBtn").on("change", (e) => {

                const file = e.target.files[0];

                _this.handleFileData(file);

            });
        },

        createScene() {

            const config = Halo.Config.get();

            const entry_scene = config.entry_scene || 'main';

            const scene = new Halo.HaloScene();

            scene.name = entry_scene;

            Editor.save('scn', entry_scene, scene);

            Halo.Config.play(entry_scene);

            return scene;
        },

        setViewPort() {

            try {

                const scene = Halo.ResourceManager.getObj('scn', Halo.Config.get().entry_scene);

                Halo.Config.setScene(scene);

                window.viewport.setviewer(scene);

            } catch (e) {
                this.$message.error("初始化模型失败: " + e.message);
            }

        },

        initViewPort() {

            window.viewport = new Viewport($('.scenesView'));

            window.viewport.resizeWindow();

            function animate() {
                requestAnimationFrame(animate);
                window.viewport.render();
            };


            animate();
        },

        showMaterialList(e, type) {

            if (type) {

                this.searchType = type;
            }

            const searchResultList = $(".searchResultList");

            searchResultList.html("").height($(".btnContent").height() - 2);


            if (e) {
                $(e.target).addClass("active").siblings().removeClass("active");
            }

            if (this.materialObj.material && (!type || type === "material")) {

                let k = "";
                let materialObjItem;

                for (k in this.materialObj.material) {

                    materialObjItem = this.materialObj.material[k];

                    materialObjItem.forEach(item => {
                        searchResultList.append(`<div> <img src="${Editor.getMaterialImage(item).src}" draggable="true" name="${item.name}" from="material"> 
                        <span>${item.name}</span> <div/>`);
                    });
                }
            }

            if (this.materialObj.textures && (!type || type === "textures")) {

                let k = "";
                let src = "";

                for (k in this.materialObj.textures) {

                    if (Halo.ResourceManager.getObj("img", k) !== null) {

                        src = Halo.ResourceManager.getObj("img", k).image.src;

                        searchResultList.append(`<div> <img src="${src}" draggable="true" name="${k}" from="textures"> 
                        <span>${k}</span> <div/>`);
                    }

                }
            }

            if (type === "text") {

                const searchResultListH = $(".contentCenterContainer .pickView").find(".searchResultList").height();
                const searchResultListW = $(".contentCenterContainer .pickView").find(".searchResultList").width();

                const _this = this;

                searchResultList.append(`<div id="addTextBtn" draggable="true"><span>点击添加文本</span> <div/>`);

                $("#addTextBtn").css({
                    width: "300px",
                    height: "44px",
                    border: "1px solid rgba(105, 108, 145, 1)",
                    borderRadius: "6px",
                    marginTop: (searchResultListH - 44) / 2 + "px",
                    marginLeft: (searchResultListW - 300) / 2 + "px",
                    lineHeight: "44px",
                    background: "transparent"

                }).on("click", _this.initCreateText);

                $("#addTextBtn span").css({
                    display: "inline",
                    fontSize: "16px",
                    fontWeight: 100,
                });


            }

            this.creatClickItemEvent($(".searchResultList>div"));


        },

        handleModelFileData(meta, fileName = "untitled") {

            const _this = this;

            Halo.ResourceManager.clearCache();

            Halo.parseProject(meta, function (res) {

                if (res === null) {

                    _this.setBaseConfig();

                    _this.materialObj.material = Vue.prototype.baseConfig.material;
                    _this.materialObj.textures = Vue.prototype.baseConfig.textures;

                    _this.setViewPort();

                    _this.$root.$emit("outLineDataChanged", true);
                    _this.$root.$emit("editorDataChanged", true);
                    _this.$root.$emit("fileParsed", fileName);
                    _this.$root.$emit("haloLoaded");

                    _this.showMaterialList();
                }
            });
        },

        setBaseConfig() {

            Vue.prototype.baseConfig = {};

            Vue.prototype.baseConfig.entry_scene = Halo.Config.get().entry_scene;
            Vue.prototype.baseConfig.light = Editor.getLights();
            Vue.prototype.baseConfig.camera = Editor.getCameras();
            Vue.prototype.baseConfig.model = Editor.getModels();
            Vue.prototype.baseConfig.material = Editor.getMaterials();
            Vue.prototype.baseConfig.textures = Halo.Config.get().textures;
            Vue.prototype.baseConfig.text = this.getRootTextWidgets(Halo.Config.get().widgets);
            Vue.prototype.baseConfig.geo = Editor.resmap("geo");

            this.materialObj.material = Vue.prototype.baseConfig.material;
            this.materialObj.textures = Vue.prototype.baseConfig.textures;

        },

        searchSources(e) {

            if (e.keyCode === 13) {

                const searchResultList = $(".searchResultList");

                searchResultList.html("");

                const searceStr = $.trim($(e.target).val());

                if (!searceStr) {
                    this.showMaterialList("", this.searchType);
                    return;
                }

                if (this.materialObj.material) {

                    let k = "";
                    let materialObjItem;

                    for (k in this.materialObj.material) {

                        materialObjItem = this.materialObj.material[k];

                        materialObjItem.forEach(item => {

                            if (item.name === searceStr) {
                                searchResultList.append(
                                    `<div> <img src="${Editor.getMaterialImage(item).src}" draggable="true" name="${item.name}" from="material">
                                    <span>${item.name}</span> <div/>`
                                );
                            }
                        });
                    }
                }

                if (this.materialObj.textures) {

                    let k = "";
                    let src = "";

                    for (k in this.materialObj.textures) {

                        if (Halo.ResourceManager.getObj("img", k) !== null && k === searceStr) {

                            src = Halo.ResourceManager.getObj("img", k).image.src;

                            searchResultList.append(`<div> <img src="${src}" draggable="true" name="${k}" from="textures"> <span>${k}</span> <div/>`);

                        }

                    }
                }

            }
        },

        creatClickItemEvent(targetArr) {

            const _this = this;

            let name = "";
            let index = 0;
            for (index; index < targetArr.length; index++) {

                const imgObj = targetArr.eq(index).find("img");

                name = imgObj.attr("name");

                targetArr.eq(index).on("click", this.setSelectedTexturesButtonStyle.bind(this, index));

                $(imgObj).on("mousedown", _this.onMouseDown);
            }
        },

        setSelectedTexturesButtonStyle(index) {

            $(".searchResultList>div>img").removeClass("selectedItem");

            $(".searchResultList>div").eq(index).children("img").addClass("selectedItem");
        },

        setMaterialMap(data) {

            this.targetObj = data.target;

            if (this.targetObj !== null && this.dropObj !== null) {

                if (this.dropObj.attr("from") === "textures") {

                    const imgName = $(this.dropObj).attr("name");
                    const imgSrc = $(this.dropObj).attr("src");
                    const mapType = $(data.target).attr("mapType");

                    $(data.target).find("img").attr("src", imgSrc);

                    $(data.target).parent().find(".texturePickTitle").text(imgName);

                    data.dataObj.material[mapType] = Halo.ResourceManager.getObj("img", imgName);
                    data.dataObj.material.needsUpdate = true;

                } else {
                    this.$message.info("贴图只支持设置图片");
                }
            }

            this.targetObj = null;

            this.dropObj = null;
        },

        onMouseDown(e) {

            const _this = this;

            const target = $(e.target);

            _this.dropObj = target;

            $(target).on("mouseup", (e) => {
                _this.onMouseUp(e);
            });
        },

        onMouseUp(e) {

            const target = $(e.target);

            if (this.targetObj === null) {
                this.dropObj = null;
            }

            $(target).off("mousedown");

            $(target).off("mouseup");
        },

        slideDownTitle() {

            const pickView = $(".contentCenterContainer .pickView");

            if (Object.keys(this.slideObj).length === 0) {

                const btnContentH = $(".contentCenterContainer .pickView").find(".btnContent").height();
                const canvasH = $(".scenesView").height() + btnContentH;

                this.slideObj["btnContentH"] = btnContentH;
                this.slideObj["canvasH"] = canvasH;
            }

            if (this.slideFlag === 0) {

                $("#contentCenter").css("display", "block");

                pickView.animate({top: this.slideObj["btnContentH"] + "px"});

                $("canvas").animate({height: this.slideObj["canvasH"] + "px"}, () => window.viewport.resizeWindow());

                $(".contentCenterContainer .pickView .title i").addClass("titleRotate");

                this.slideFlag = 1;

            } else {

                pickView.animate({top: 0});

                $("canvas").animate({height: this.slideObj["canvasH"] - this.slideObj["btnContentH"] + "px"}, () => {
                    window.viewport.resizeWindow();
                    $("#contentCenter").css("display", "flex");
                });

                $(".contentCenterContainer .pickView .title i").removeClass("titleRotate");

                this.slideObj = {};
                this.slideFlag = 0;
            }

        },

        getRootTextWidgets(widgets) {

            const widgetsObj = {};

            let k = "";
            for (k in widgets) {
                if (widgets[k].class === "WtText") {
                    widgetsObj[widgets[k].name] = widgets[k];
                }
            }

            return widgetsObj;
        },

        initCreateText(e) {

            const wtText = Editor.createWidget("WtText");

            wtText.offsetX = 100;
            wtText.offsetY = 100;
            wtText.sizeX = 100;
            wtText.sizeY = 100;

            Halo.Config.get().widgets[wtText.name] = wtText;

            Halo.Config.scene().getWidgetRoot().add(Halo.Config.createWidget(wtText.name));

            Vue.prototype.baseConfig.text = this.getRootTextWidgets(Halo.Config.get().widgets);

            if (!Halo.Config.scene()._widgets || Halo.Config.scene()._widgets === null) {
                Halo.Config.scene()._widgets = [];
            }

            Halo.Config.scene()._widgets.push(wtText.name);

            this.$root.$emit("outLineDataChanged");
        },

        uploadResources() {

            const app = $("#app");

            let domStr = `<div class="uploadFileView"> 
                            <div class="uploadTitle"><span>上传文件</span> <button class="el-icon-close"></button> </div>
                            
                            <div class="uploadCenter">
                                <button class="uploadBtnContent"> <span>上传</span> <input type="file" id="fileBtn" accept="image/png,image/jpg,image/jpeg,.halo,.fbx"> </button> 
                                <span>将文件拖拽至此处或点击上传</span> 
                                <span><span></span><i class="el-icon-success"></i></span> 
                            </div>
                            
                            <div class="tips"> <p>
                                目前我们支持的文件上传格式有: <br>
                                模型格式：fbx <br>
                                模型+材质的压缩格式：halo <br>
                                图片格式：jpg，png
                            </p> <i></i></div>
                            <div class="uploadFooter"><span>文件规格?</span></div>
                          </div>`;

            $(".scenesView").append(domStr);

            const uploadFileView = $(".uploadFileView");
            const uploadCenterSpan = $(".uploadFileView .uploadCenter>span");

            uploadFileView.css({
                left: app.width() / 2 - uploadFileView.width() / 2 + "px",
                top: app.height() / 2 - uploadFileView.height() / 2 + "px",
            }).fadeIn(300);


            uploadFileView.find(".uploadTitle button").on("click", () => {
                uploadFileView.fadeOut(300, () => uploadFileView.remove());
            });

            $(".uploadFooter span").on('mouseenter', () => $(".tips").fadeIn())
                .on("mouseleave", () => $(".tips").fadeOut());

            uploadCenterSpan.eq(1).hide();
            uploadCenterSpan.eq(1).find("span").text("");


            this.createUploadFileEvent();

            this.createDropFileEvent(uploadFileView);
        },

        createDropFileEvent(target) {

            const _this = this;

            target.on("drop", (e) => {

                e.preventDefault();

                const files = e.originalEvent.dataTransfer.files;

                if (files.length < 1 || !files[0]) return;

                const fileType = BaseUtil.getFileType(files[0].name).toLowerCase();
                const findRes = ['fbx', 'halo', 'png', 'jpg', 'jpeg'].find((type) => type === fileType);

                if (!findRes) {
                    _this.$message.warning("请上传指定类型文件");
                    return;
                }

                _this.handleFileData(files[0]);
            });

        },

        async handleFileData(file) {

            if (!file) return;

            const _this = this;
            const fileType = BaseUtil.getFileType(file.name);

            if (fileType === "halo") {

                _this.$root.$emit("fileOnChanged");

                const reader = new FileReader();

                reader.readAsArrayBuffer(file);

                reader.onload = async () => {

                    const data = new Uint8Array(reader.result);

                    if (!window.Halo) {

                        const zipFileLoaded = new JSZip(data, { "uint8array": true });
                        const keys = Object.keys(zipFileLoaded.files);
                        const contents = zipFileLoaded.files[keys[0]].asText();
                        const metaObj = JSON.parse(contents);

                        await _this.createHaloScript(metaObj.cfg.version);

                        _this.initViewPort();

                        this.initHaloProject();
                    }

                    const meta = Halo.ResourceManager.unzip(data);

                    _this.handleModelFileData(meta, file.name);

                    $(".uploadFileView .uploadCenter>span").show().eq(1).find("span").text(file.name);

                    const timer = setTimeout(() => {

                        const uploadFileView = $(".uploadFileView");

                        uploadFileView.fadeOut(() => uploadFileView.remove());

                        clearTimeout(timer);

                    }, 1500);
                };

                return;
            }

            if (!window.Halo) {

                await _this.createHaloScript("new");

                _this.initViewPort();

                this.initHaloProject();

            }

            if (fileType.toLowerCase() === "fbx") {

                BaseUtil.parseFbx(file, (group) => {

                    _this.createSelectObjView(Editor.getDepsNObj(group), group);

                    $(".uploadFileView .uploadCenter>span").show().eq(1).find("span").text(file.name);

                    this.$root.$emit("haloLoaded");

                    const timer = setTimeout(() => {

                        const uploadFileView = $(".uploadFileView");

                        uploadFileView.fadeOut(() => uploadFileView.remove());

                        clearTimeout(timer);



                    }, 1500);
                });

                return;
            }

            if (fileType.toLowerCase() === "png" || fileType.toLowerCase() === "jpg") {

                Editor.readFile(file, true, (data) => {

                    const img = new Image();

                    img.onload = () => {

                        img.name = file.name;

                        Editor.save("img", img.name, img);

                        const cfg = Halo.Config.get();

                        if (!cfg.textures) cfg.textures = {};

                        cfg.textures[img.name] = {type: 'image'};

                        if (!Vue.prototype.baseConfig) {

                            Vue.prototype.baseConfig = {};
                            Vue.prototype.baseConfig.textures = {};

                        } else if (Vue.prototype.baseConfig.textures) {

                            Vue.prototype.baseConfig.textures = {};
                        }

                        Vue.prototype.baseConfig.textures = Halo.Config.get().textures;

                        _this.$root.$emit("outLineDataChanged");

                        $(".uploadFileView .uploadCenter>span").show().eq(1).find("span").text(file.name);
                    };

                    img.onerror = () => _this.$message.error(file.name + " 加载错误");

                    img.src = data;

                    _this.$root.$emit("haloLoaded");
                });
            }

        },

        createSelectObjView(objList, mdl) {

            if (!objList instanceof Array || objList.length === 0) return;

            let domStr = '<div class="objPickView"> ' +
                '<div class="objPickTitle"><button class="el-icon-close closeBtn"></button></div> ' +
                '<div class="objPickContent"></div>' +
                '<div class="objPickFoot">' +
                '<div><input type="checkbox" checked="checked"> 全选</div>' +
                '<div><button id="importObjBtn">导入</button></div>' +
                '</div>' +
                '</div>';

            $(".scenesView").append(domStr);

            $(".scenesView .objPickView").css("left", $("#app").width() / 2 - 563 / 2 + "px");

            $(".scenesView .objPickView .objPickContent").html(this.setSelectObjViewContentChildren(objList, mdl));

            const timer = setTimeout(() => {
                $(".objPickView").fadeIn();
                clearTimeout(timer);
            }, 1300);

            this.createButtonEvent($(".scenesView .objPickView .objPickTitle .el-icon-close.closeBtn"));
            this.createButtonEvent($(".scenesView .objPickView #importObjBtn"), mdl.name);

            this.setCheckedType();
        },

        setSelectObjViewContentChildren(objList, mdl) {

            objList.push(mdl);

            let objPickContentChildren = "";

            objList.forEach((item, index) => {

                const type = item.path || "mdl";

                if (index % 2 === 0) {
                    objPickContentChildren += '<div>' +
                        '<input type="checkbox" checked="checked">' +
                        '<span class="objType">' + type + '</span>' +
                        '<span class="objName">' + item.name + '</span>' +
                        '</div>';
                } else {

                    objPickContentChildren += '<div class="ColumnColor">' +
                        '<input type="checkbox" checked="checked">' +
                        '<span class="objType">' + type + '</span>' +
                        '<span class="objName">' + item.name + '</span>' +
                        '</div>';
                }

            });

            this.paresModelObj = objList;

            return objPickContentChildren;
        },

        createButtonEvent(target, fileName) {

            if (!target) return;

            target.on("click", () => {

                if (target.attr("id") && target.attr("id") === "importObjBtn") {

                    const selectObjChildren = $(".scenesView .objPickView .objPickContent").children();

                    let i = 0;
                    for (i; i < selectObjChildren.length; i++) {

                        if (selectObjChildren.eq(i).find("input").get(0).checked) {

                            const itemObj = this.paresModelObj[i];

                            if (itemObj.hasOwnProperty("path")) {
                                Editor.save(itemObj.path, itemObj.name, itemObj.obj);
                            } else if (itemObj.type === "Group") {
                                Editor.save("mdl", itemObj.name, itemObj);
                            }

                        }
                    }

                    const scene = Halo.Config.scene();

                    if (scene !== null && selectObjChildren.eq(this.paresModelObj.length - 1).find("input").get(0).checked) {

                        scene.add(this.paresModelObj[this.paresModelObj.length - 1]);

                    } else if (scene === null){

                        const newScene = this.createScene();

                        Editor.save("scn", newScene.name, newScene);

                        Halo.Config.get().entry_scene = newScene.name;

                        if (selectObjChildren.eq(this.paresModelObj.length - 1).find("input").get(0).checked) {
                            newScene.add(this.paresModelObj[this.paresModelObj.length - 1]);
                        }

                        this.setViewPort();

                    }

                    const geoSet = this.paresModelObj.filter(item => item.path && item.path === "geo");
                    const modelSet = Editor.getModels();

                    let idx = 0;
                    for (idx; idx < geoSet.length; idx ++) {

                        const models = BaseUtil.getUsedModelSet("geo", geoSet[idx].name, modelSet);

                        if (models.length > 0) BaseUtil.setUsedModel("geo", geoSet[idx], models);

                    }

                    this.setBaseConfig();

                    this.$root.$emit("outLineDataChanged", true);
                    this.$root.$emit("editorDataChanged", true);
                    this.$root.$emit("fileParsed", fileName);

                    this.showMaterialList();
                }

                $(".scenesView .objPickView ").fadeOut(300, () => {
                    $(".scenesView .objPickView").remove();
                });
            });
        },

        setCheckedType() {

            const checkedAllBtn = $(".scenesView .objPickView .objPickFoot input");
            const objCheckList = $(".scenesView .objPickView .objPickContent input");

            checkedAllBtn.on("change", (e) => {

                let isCheckedAll = $(e.target).get(0).checked;

                if (isCheckedAll) {

                    for (let i = 0; i < objCheckList.length; i++) {

                        if (!objCheckList.eq(i).get(0).checked) {
                            objCheckList.eq(i).get(0).checked = true;
                        }
                    }

                } else {

                    for (let i = 0; i < objCheckList.length; i++) {

                        if (objCheckList.eq(i).get(0).checked) {
                            objCheckList.eq(i).get(0).checked = false;
                        }
                    }
                }
            });

        },

        createHaloScript (version="new") {

            const _this = this;

            return new Promise((resolve, reject) => {

                const haloVersion = EditorDefaultConf.haloVersion[version] || EditorDefaultConf.haloVersion["new"];
                const halofile = `${EnvConf[process.env.NODE_ENV]['sourceDownLoadUrl']}halo-${haloVersion}.min.js`;
                const script = document.createElement('script');
                script.type = "text/javascript";

                script.onload = async () => {

                    await _this.createScriptElement("FBXLoader2.js");
                    await _this.createScriptElement("TransformControls.js");
                    await _this.createScriptElement("EditorControls.js");
                    await _this.createScriptElement("Viewport.js");
                    await _this.createScriptElement("Editor.js");

                    resolve();
                };

                script.src = halofile;

                document.head.appendChild(script);
            })

        },

        createScriptElement (src) {

            return new Promise((resolve, reject) => {

                const script = document.createElement('script');

                script.type = "text/javascript";
                script.src = EnvConf[process.env.NODE_ENV]['sourceDownLoadUrl'] + src;

                script.onload = () => {
                    resolve();
                };

                document.head.appendChild(script);

            });

        },

        initHaloProject () {

            Halo.Config.bEditor = true;
            Halo.init(null, "/assets/");
            Halo.Storage.init('FRONTEDITOR');
            const cfg = Halo.Config.get();
            Object.assign(cfg, {
                version: '0.1f',
                alpha: false,
                antialias: false,
                preserveDrawingBuffer: false,
                shadowMapType: 1,
                design_size: { x: 1920, y: 1080 },
                textures: {},
                effects: {},
                widgets: {},
                audios: {},
                dragonbones: [],
                batches: {}
            });

        },
    }
}